package com.jlnk.androidfmc;

import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.jlnk.androidfmc.adapter.AddressAdapter;
import com.jlnk.androidfmc.entity.Address;
import com.jlnk.androidfmc.model.AddressVM;
import com.kongzue.dialogx.citypicker.CityPickerDialog;
import com.kongzue.dialogx.citypicker.interfaces.OnCitySelected;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;


import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class AddressActivity extends AppCompatActivity {

  private AddressVM viewModel;
  private AddressAdapter adapter;
  private Toolbar toolbar;
  private RecyclerView rcl;
  private FloatingActionButton fab;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_address);
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
      Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
      v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
      return insets;
    });
    Tools.setSystemBarColorInt(this, Color.parseColor("#FFFFFF"));

    viewModel = new ViewModelProvider(this).get(AddressVM.class);

    init();
  }

  private void init() {
    initView();
  }

  private void initView() {
    toolbar = findViewById(R.id.toolbar);
    rcl = findViewById(R.id.rcl);
    fab = findViewById(R.id.fab);
    initToolbar();
    initRcl();
    initFab();
  }

  private void initToolbar() {
    setSupportActionBar(toolbar);
    Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
  }

  private void initRcl() {
    rcl.setLayoutManager(new LinearLayoutManager(this));
    adapter = new AddressAdapter(this::showDialog);
    initData();
    rcl.setAdapter(adapter);
  }

  private void initData() {
    List<Address> addresses = viewModel.queryAll();
    adapter.insertAllItems(addresses);
  }

  private void initFab() {
    fab.setOnClickListener(v -> {
      showDialog(new Address());
    });
  }

  private void showDialog(Address address) {
    BottomDialog dialog = BottomDialog.build(
        new OnBindView<BottomDialog>(R.layout.dialog_address) {
          @Override
          public void onBind(BottomDialog bottomDialog, View view) {
            RadioButton rbIsDefault = view.findViewById(R.id.rb_is_default);
            MaterialButton btnSubmit = view.findViewById(R.id.submit);
            TextView tvTitle = view.findViewById(R.id.title);
            TextInputEditText edName, edPhone, edAddress, edAddressDetail;
            edName = view.findViewById(R.id.ed_name);
            edPhone = view.findViewById(R.id.ed_phone);
            edAddress = view.findViewById(R.id.ed_address);
            edAddressDetail = view.findViewById(R.id.ed_address_detail);

            rbIsDefault.setChecked(address.getIsDefault() == 1);
            edName.setText(address.getName());
            edPhone.setText(address.getPhone());
            if (address.getId() != 0) {
              tvTitle.setText("编辑收货地址");
              edAddress.setText(
                  address.getProvince() + " " + address.getCity() + " " + address.getDistrict());
            }
            edAddressDetail.setText(address.getAddressDetail());

            AtomicBoolean isChecked = new AtomicBoolean(address.getIsDefault() == 1);
            rbIsDefault.setOnClickListener(v -> {
              isChecked.set(!isChecked.get());
              rbIsDefault.setChecked(isChecked.get());
            });

            edAddress.setOnClickListener(v -> {
              CityPickerDialog.build().show(new OnCitySelected() {
                @Override
                public void onSelect(String text, String province, String city, String district) {
                  address.setProvince(province);
                  address.setCity(city);
                  address.setDistrict(district);
                  edAddress.setText(province + " " + city + " " + district);
                }
              });
            });

            btnSubmit.setOnClickListener(v -> {
              String name = Objects.requireNonNull(edName.getText()).toString();
              String phone = Objects.requireNonNull(edPhone.getText()).toString();
              String addressDetail = Objects.requireNonNull(edAddressDetail.getText()).toString();
              if (name.isEmpty() || phone.isEmpty() || edAddress.getText().toString().isEmpty()
                  || addressDetail.isEmpty()) {
                Toast.makeText(App.getContext(), "请填写完整", Toast.LENGTH_SHORT).show();
                return;
              }
              address.setName(name);
              address.setPhone(phone);
              address.setAddressDetail(addressDetail);
              address.setIsDefault(rbIsDefault.isChecked() ? 1 : 0);
              if (address.getId() == 0) {
                address.setId(new Random().nextInt(1000000));
                viewModel.insert(address);
                adapter.insertItem(address);
              } else {
                viewModel.update(address, address.getIsDefault() == 1);
                adapter.updateItem(address);
              }
              bottomDialog.dismiss();
            });
          }
        });
    dialog.show();
  }


  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
      finish();
    }
    return super.onOptionsItemSelected(item);
  }
}